package com.difsonapps.android.joinme;

import java.util.List;

import com.difsonapps.android.joinme.R;
import com.difsonapps.android.joinme.db.Contact;
import com.difsonapps.android.joinme.db.DatabaseHandler;
import com.difsonapps.android.joinme.util.NetUtils;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.util.ArrayList;

import org.w3c.dom.Document;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.Overlay;

import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;



public class HomeFragment extends Fragment implements LocationListener {
	
	long id;
	DatabaseHandler db;
	
    private GoogleMap googleMap;
    Location location ;
	private View rootView;
	private Activity MActivity;
	
	
   List<Overlay> mapOverlays;
   GeoPoint point1, point2;
   LocationManager locManager;
   Drawable drawable;
   Document document;
   GMapV2GetRouteDirection v2GetRouteDirection;
   LatLng fromPosition;
   LatLng toPosition;
   MarkerOptions markerOptions;
   Boolean routOK = true; 
   String DeviceIpAddress; 
	public HomeFragment(){}

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		if(rootView == null){
	        rootView = inflater.inflate(R.layout.fragment_home, container, false);
	        refrechView();  
		}
		MActivity = this.getActivity();
		
        // Setting Zoom Controls on MapView
		googleMap.setMyLocationEnabled(true);
		googleMap.getUiSettings().setCompassEnabled(true);
		googleMap.getUiSettings().setMyLocationButtonEnabled(true);
		googleMap.getUiSettings().setAllGesturesEnabled(true);
		markerOptions = new MarkerOptions();
		v2GetRouteDirection = new GMapV2GetRouteDirection();
		LocationManager locationManager = (LocationManager) MActivity.getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);       
        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);
        if(location!=null){
            onLocationChanged(location);
            ZomingToLocation(location);
            
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, this);	
        
        DeviceIpAddress = NetUtils.getIPAddress(true);
        Log.d("IP Address",DeviceIpAddress );
        
        
//		Intent intent = this.getActivity().getIntent();
//		String idContact = intent.getStringExtra("id");
//		id = Long.valueOf(idContact);
//		db = new DatabaseHandler(this.getActivity().getApplicationContext());
//		Uri dataUri = ContactsContract.Data.CONTENT_URI;
//		Cursor dataCursor = this.getActivity().getContentResolver().query(dataUri, null, 
//				ContactsContract.Data.CONTACT_ID + "=" + id, 
//				null, null);
//		Contact contact = db.getContactContactId(id);
//		if(contact==null)
//		{
//			
//			return rootView;
//		}
//		getActivity().getActionBar().setTitle(contact.getName());
		return rootView;
	}
	
	
	public void refrechView(){
	  try {
	      // Loading map
	      initilizeMap();
	
	  } catch (Exception e) {
	      e.printStackTrace();
	  }     
	}


	private void initilizeMap() {
		
	  if (googleMap == null) {
	      googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
	
	      // check if map is created successfully or not
	      if (googleMap == null) {
	       //   Toast.makeText(t,"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
	      }
	  }
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
        //TextView tvLocation = (TextView) findViewById(R.id.tv_location);
        
		this.location=location;
//		if(routOK)
//		{
//		       fromPosition = new LatLng(location.getLatitude(), location.getLongitude());     
//		       toPosition = new LatLng(location.getLatitude()+0.1, location.getLongitude()+0.1);
//		       GetRouteTask getRoute = new GetRouteTask();
//		       getRoute.execute();
//		       routOK=false;
//		}

	}
	
	public  void ZomingToLocation(Location location)
	{
        // Getting latitude of the current location
        double latitude = location.getLatitude();
 
        // Getting longitude of the current location
        double longitude = location.getLongitude();
 
        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);
 
        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
 
        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
 
        // Setting latitude and longitude in the TextView tv_location
        //tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );
//	       googleMap.addMarker(new MarkerOptions()
//           .position(latLng)
//           .title("My Spot")
//           .snippet("This is my spot!")
//           .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));

		
	}
	

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	
	
    private class GetRouteTask extends AsyncTask<String, Void, String> {
        
        private ProgressDialog Dialog;
        String response = "";
        @Override
        protected void onPreExecute() {
              Dialog = new ProgressDialog(MActivity);
              Dialog.setMessage("Loading route...");
              Dialog.show();
        }

        @Override
        protected String doInBackground(String... urls) {
              //Get All Route values
                    document = v2GetRouteDirection.getDocument(fromPosition, toPosition, GMapV2GetRouteDirection.MODE_WALKING);
                    response = "Success";
              return response;

        }

        @Override
        protected void onPostExecute(String result) {
        	googleMap.clear();
              if(response.equalsIgnoreCase("Success")){
              ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
              PolylineOptions rectLine = new PolylineOptions().width(10).color(
                          Color.RED);

              for (int i = 0; i < directionPoint.size(); i++) {
                    rectLine.add(directionPoint.get(i));
              }
              // Adding route on the map
              googleMap.addPolyline(rectLine);
              markerOptions.position(toPosition);
              markerOptions.draggable(true);
              googleMap.addMarker(markerOptions);

              }
             
              Dialog.dismiss();
              routOK=true;
        }
  }
	
	
	
}
